package data.join.com.utils;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.google.gson.Gson;


public class QuickShPref {
	public final static String DeviceImei = "DeviceImei";
	public final static String LockVideoEnable = "LockVideoEnable";
	public final static String LastStartLock = "LastStartLock";

	public final static String LastTimeAccOn = "LastTimeAccOn";
	public final static String LastTimeAccOff = "LastTimeAccOff";

	public final static String InitDevConfig = "InitDevConfig";

	private Context mContext;
	private boolean isMainProcess;
	private String mPrefName;

	private static QuickShPref quickShPref;

	private QuickShPref(Application c){
		mContext = c;
		isMainProcess = true;
	}

	public static QuickShPref getInstance(){
		return quickShPref;
	}

	public static void init(Application c){
		quickShPref = new QuickShPref(c);
	}

	synchronized public void putValueObject(String key , Object obj){
		synchronized (mContext) {
			Editor sEditor = getPref().edit();
			if (obj instanceof String) {
				sEditor.putString(key, (String) obj);
			} else if (obj instanceof Integer) {
				sEditor.putInt(key, (Integer) obj);
			} else if (obj instanceof Long) {
				sEditor.putLong(key, (Long) obj);
			} else if (obj instanceof Boolean) {
				sEditor.putBoolean(key, (Boolean) obj);
			} else if (obj instanceof Float) {
				sEditor.putFloat(key, (Float) obj);
			} else {
				return;
			}
			sEditor.commit();
		}
	}

	public String getString(String key){
		String ret = null;
		synchronized (mContext) {
			ret = getPref().getString(key, "");
		}
		return ret;
	}
	public int getInt(String key){
		int ret = -1;
		synchronized (mContext) {
			 ret = getPref().getInt(key, -1);
		}
		return ret;
	}
	public boolean getBoolean(String key){
		boolean ret = false;
		synchronized (mContext) {
			 ret = getPref().getBoolean(key, false);
		}
		return ret;
	}
	public Float getFloat(String key){
		Float ret = null;
		synchronized (mContext) {
			 ret = getPref().getFloat(key, 0f);
		}
		return ret;
	}
	public Long getLong(String key){
		Long ret = null;
		synchronized (mContext) {
			ret = getPref().getLong(key, 0L);
		}
		return ret;
	}

	public <T> T getClass(String key, Class<T> classOfT){
		String json = getString(key);
		T obj = null;
		if(TextUtils.isEmpty(json) == false) {
			obj = new Gson().fromJson(json, classOfT);
		}
		return obj;
	}

	public <T> void putGsonClass(String key,T t){
		String json = new Gson().toJson(t);
		putValueObject(key,json);
	}

	public SharedPreferences getPref(){
		return mContext.getSharedPreferences(getPrefName(), Context.MODE_PRIVATE);
	}

	private String getPrefName(){
		if(TextUtils.isEmpty(mPrefName)){
			mPrefName = mContext.getPackageName() + "_" + isMainProcess;
		}
		return mPrefName;
	}
}
